package com.zking.utils;

import com.zking.entity.User;

import java.io.*;

public class SerializeUtils {
	/**
	 * 将对象进行序列化
	 * @param obj 需要序列化的对象
	 * @return
	 * @throws IOException
	 */
	public static String serialize(Object obj) throws IOException {
		//字节数组输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //序列化的对象输出流
        ObjectOutputStream objectOutputStream;
        //字节数组输出流交给对象输出流
        objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        //将对象的内容写入
        objectOutputStream.writeObject(obj);
        //再由字节数组输出流得到序列化之后的字符串
        String string = byteArrayOutputStream.toString("ISO-8859-1");
        //关闭资源
        objectOutputStream.close();
        byteArrayOutputStream.close();
        return string;
    }
	
	/**
	 * 获取序列化之后的对象，再转化为对象
	 * @param str 序列化之后的字符串
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
    public static Object serializeToObject(String str) throws IOException, ClassNotFoundException {
        //创建一个字节数组输入流，编码是ISO-8859-1
    	ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Object object = objectInputStream.readObject();
        objectInputStream.close();
        byteArrayInputStream.close();
        return object;
    }
    
    public static void main(String[] args) throws IOException, ClassNotFoundException {
		User user1 = new User();
		user1.setUsername("admin");
		System.out.println(SerializeUtils.serialize(user1));
		System.out.println(SerializeUtils.serializeToObject(SerializeUtils.serialize(user1)));
	}
    
}
